package com.ganinfo.common.token;
import java.util.UUID;

import javax.servlet.http.HttpSession;

public class SessionToken implements IToken{
	
	private static HttpSession session = null;
	
	public SessionToken(Object o){
		//System.out.println("进入");
		SessionToken.session=(HttpSession) o;
	}

	@Override
	public String login(String userid) {
		//判断是否已经登录，若是，清除session中的记录
		if(session.getAttribute(userid) != null){
			delToken(userid);
		}
		//添加新的登录信息
		String uuid = getUUID();
		session.setAttribute(uuid, userid);
		session.setAttribute(userid, uuid);
		System.out.println("登录时放入session的uuid:"+session.getAttribute(userid));
		System.out.println("登录时放入session的userid:"+session.getAttribute(uuid));
		session.setMaxInactiveInterval(30*60);
		
		//返回token,作为登录凭证
		return uuid;
	}

	@Override
	public void logout(String userid) {
		session.invalidate();
		
	}

	@Override
	public boolean validate(String token) {
		String userid = (String) session.getAttribute(token);
		System.out.println("登录验证功能中session里的userid:"+userid);
		if(userid != null){
			return true;
		}else{
			return false;
		}
		
	}
	
	public String getUUID() {
		String uuid = UUID.randomUUID().toString().replace("-", "");
		return uuid;
	}
	
	public void delToken(String userid) {
		String uuid = (String)session.getAttribute(userid);
		session.removeAttribute(userid);
		session.removeAttribute(uuid);
		
	}
	

}
